Backbone.View.prototype.close = function () {
    if (this.beforeClose) {
        this.beforeClose();
    }
    this.remove();
    this.unbind();
};

var AppRouter = Backbone.Router.extend({

    initialize:function () {
        /*$('#header').html(new HeaderView().render().el);*/
    },

    routes:{
        "":"list",
        "list":"list",
        "business/new":"newBusiness",
        "business/:id":"businessDetails",
        "business/update/:id":"updateBusinessDetails"
    },

    list:function () {
        this.before();
    },

    businessDetails:function (id) {
        this.before(function () {
            var business = app.businessList.get(id);
            app.showView('#content', new BusinessView({model:business}));
        });
    },

    updateBusinessDetails:function (id) {
        this.before(function () {
            var business = app.businessList.get(id);
            app.showView('#content', new BusinessForm({model:business}));
        });
    },

    newBusiness:function () {
        this.before(function () {
            app.showView('#content', new BusinessForm({model:new Business()}));
        });
    },

    showView:function (selector, view) {
        if (this.currentView)
            this.currentView.close();
        $(selector).html(view.render().el);
        this.currentView = view;
        return view;
    },

    before:function (callback) {
        if (this.businessList) {
            if (callback) callback();
        } else {
            this.businessList = new BusinessCollection();
            this.businessList.fetch({success:function () {
                $('#sidebar').html(new BusinessListView({model:app.businessList}).render().el);
                if (callback) callback();
            }});
        }
    }

});

tpl.loadTemplates([ 'business/business-details', 'business/business-list-item','business/business-update'], function () {
    app = new AppRouter();
    Backbone.history.start();
});